<template>
  <el-dialog :title="`${title || '选择文件夹'}`" :visible.sync="show" :close-on-click-modal="false" width="500px" append-to-body @closed="closed">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="选择文件夹" prop="taskFileId">
        <treeselect v-model="form.taskFileId" :options="folderTree" :normalizer="folderNormalizer" placeholder="请选择文件夹" no-results-text="暂无数据匹配" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="folderLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="folderLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 选择文件夹
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { debounce } from '@/utils'
import { flatList2tree } from '@/utils'
import { listRdcTaskFile } from '@/api/projectInspection/courseCheck'
export default {
  components: { Treeselect },
  props: { title: { type: String, default: '' } },
  data() {
    return {
      show: false,
      form: { taskFileId: '' },
      taskId: '',
      fileType: '',
      rootPathName: '',
      folderLoading: false,
      folderTree: []
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
  },
  methods: {
    closed() {
      this.$refs.form.resetFields()
      this.taskId = ''
      this.fileType = ''
      this.folderTree = []
    },
    async open({ taskId, fileType, rootPathName }) {
      if (!taskId || !fileType) return this.msgError('无效参数')
      this.taskId = taskId
      this.fileType = fileType
      this.rootPathName = rootPathName || ''
      this.show = true
      this.getFolderTree()
    },
    async getFolderTree() {
      const opt = {
        taskId: this.taskId,
        fileType: this.fileType,
        isFolder: 1
      }
      this.folderLoading = true
      const res = await listRdcTaskFile(opt).catch(() => false)
      this.folderLoading = false
      if (res === false) return (this.folderTree = [])

      let data = res.data || []
      data = flatList2tree(data, { id: 'taskFileId' })
      this.folderTree = [{ taskFileId: '', fileName: this.rootPathName || '根目录', children: data }]
    },
    folderNormalizer(node) {
      if (!node.children?.length) delete node.children
      return { id: node.taskFileId, label: node.fileName, children: node.children }
    },
    async onSubmit() {
      const opt = { ...this.form }
      this.$emit('selected', opt)
      this.show = false
    }
  }
}
</script>
